import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router'
import { NzMessageService } from 'ng-zorro-antd'
import { STColumn, STData } from '@delon/abc'
import { ACLService } from '@delon/acl'
import { SettingsService } from '@delon/theme'
import { I18NService } from '@core'
import { levelOption, IBatchImportFile } from '@shared/interfaces/batch-import'
import { FileService } from '@shared/services/file.service'
import { BatchImportService } from '../batch-import.service'
import { FormGroup, FormBuilder } from '@angular/forms'
import { HttpClient, HttpEventType, HttpResponse, HttpEvent, HttpRequest } from '@angular/common/http'
import { FileUploadService } from '@shared/services/upload.service'
import { IStoreQueryParams, Store } from '@shared/interfaces/store'
import { ListBaseClass } from '@shared/classes/ListBaseClass'
import { EUserType } from '@shared/enums'
import { BatchStatusTextMap } from '@shared/interfaces/common'

@Component({
  selector: 'app-new',
  templateUrl: './new.component.html',
  styleUrls: ['../../../shared/styles/new-page-form.less', './new.component.less', '../../../shared/styles/table.less'],
})
export class NewComponent extends ListBaseClass<Store, IStoreQueryParams> implements OnInit {
  data: []
  columns: STColumn[] = []
  levelOptions = levelOption
  authorizationFileList: any
  level: string
  validateForm: FormGroup
  actionUrl: string
  xhr: XMLHttpRequest
  batchResult: any
  currentFile: any
  BatchStatusTextMap = BatchStatusTextMap

  @ViewChild('fileUploadBook') fileUploadBook: any // 获取授权书文件上传dom
  constructor(
    public msg: NzMessageService,
    public i18n: I18NService,
    public router: Router,
    public route: ActivatedRoute,
    public settings: SettingsService,
    public aclService: ACLService,
    private uploderService: FileUploadService,
    private fileService: FileService,
    private batchImportService: BatchImportService,
    public fb: FormBuilder,
    private http: HttpClient,
  ) {
    super(msg, i18n, route, router, settings)
  }

  ngOnInit(): void {
    this.initColumns()
    this.initAcquirer()
  }

  handleFileUploadBook() {
    this.uploderService.handleFileUpload(this.fileUploadBook, (data: any) => {
      this.authorizationFileList = [data]
      const checkFileValid = this.fileService.validateFile({ name: data.name }, this.level)
      if (checkFileValid) {
        const key = (this.authorizationFileList[0].key = this.fileService.getFileKey({ name: data.name }))
        // 向后端发起新增批导的请求 获取上传文件的地址
        this.batchImportService.uploadUrl(key).subscribe(res => {
          this.xhr = new XMLHttpRequest()
          this.xhr.open('put', res.url)
          this.xhr.send(data.Files)
          this.xhr.onreadystatechange = this.sendState.bind(this)
        })
      }
      return
    })
  }

  sendState() {
    if (this.xhr.readyState === XMLHttpRequest.DONE && this.xhr.status === 200) {
      const file = (this.currentFile = this.authorizationFileList[0])
      const params = {
        fileKey: file.key,
        fileName: file.name,
      }
      this.batchImportService.uploadFile(params).subscribe(
        next => {
          const conn = new WebSocket(`wss://${document.location.host}/comb/ws/${next}`)
          conn.onopen = function(event) {
            // socket 开启后执行，可以向后端传递信息
            conn.send('START')
          }
          conn.onmessage = evt => {
            const dataes = evt.data.split('\n')
            dataes.forEach((item, i) => {
              const data = JSON.parse(item)
              const payload = data.payload
              const results = {
                processResult: 0,
                message: '',
              }
              switch (data.type) {
                case 0:
                  // 0 表示处理完成信息
                  results.processResult = payload.result
                  results.message = payload.msg
                  break
                case 1:
                  // 1 表示进度信息
                  break
                case 2:
                  // 2 表示终止
                  results.processResult = payload.result
                  results.message = payload.msg
                  break
                default:
                  break
              }
              if (data.type === 0 || data.type === 2) {
                this.renderList.bind(this, results)()
                conn.close(1000, 'FINISH')
              }
            })
          }
          conn.onerror = function(event) {
          }
        },
        err => {
          this.renderListError.bind(this, err)()
        },
      )
    }
  }

  initAcquirer(): void {
    if (this.authUser.userType === EUserType.Store) {
      this.levelOptions = this.levelOptions.slice(1)
    }
  }

  renderList(err): void {
    const limit = this.currentFile.size
    let size = ''
    if (limit < 0.1 * 1024) {
      // 小于0.1KB，则转化成B
      size = limit.toFixed(2) + 'B'
    } else if (limit < 0.1 * 1024 * 1024) {
      // 小于0.1MB，则转化成KB
      size = (limit / 1024).toFixed(2) + 'KB'
    } else if (limit < 0.1 * 1024 * 1024 * 1024) {
      // 小于0.1GB，则转化成MB
      size = (limit / (1024 * 1024)).toFixed(2) + 'MB'
    } else {
      // 其他转化成GB
      size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
    }
    const response = {
      size,
      filename: this.currentFile.name,
      msg: err.message,
      status: err.processResult,
    }
    this.batchResult.push(response)
    const batchResults = {
      data: this.batchResult,
      total: this.batchResult.length,
    }
    const { data, total } = batchResults
    this.data = data
    this.total = total
    this.loading = false
    this.st.load()
  }

  renderListError(err): void {
    const limit = this.currentFile.size
    let size = ''
    if (limit < 0.1 * 1024) {
      // 小于0.1KB，则转化成B
      size = limit.toFixed(2) + 'B'
    } else if (limit < 0.1 * 1024 * 1024) {
      // 小于0.1MB，则转化成KB
      size = (limit / 1024).toFixed(2) + 'KB'
    } else if (limit < 0.1 * 1024 * 1024 * 1024) {
      // 小于0.1GB，则转化成MB
      size = (limit / (1024 * 1024)).toFixed(2) + 'MB'
    } else {
      // 其他转化成GB
      size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
    }
    const response = {
      size,
      filename: this.currentFile.name,
      msg: err.error,
      status: '0',
    }
    this.batchResult.push(response)
    const batchResults = {
      data: this.batchResult,
      total: this.batchResult.length,
    }
    const { data, total } = batchResults
    this.data = data
    this.total = total
    this.loading = false
    this.st.load()
  }

  customReq = item => {
    const checkFileValid = this.fileService.validateFile({ name: item.file.name }, this.level)
    this.authorizationFileList = [item.file]
    if (checkFileValid) {
      const key = this.fileService.getFileKey({ name: item.file.name })
      this.authorizationFileList[0].key = key
      this.batchImportService.uploadUrl(key).subscribe(res => {
        this.xhr = new XMLHttpRequest()
        this.xhr.open('put', res.url)
        this.xhr.send(item.file)
        this.xhr.onreadystatechange = this.sendState.bind(this)
      })
    } else {
      return null
    }
  }

  private initColumns() {
    this.columns = [
      {
        title: '文件名',
        i18n: 'BATCH.IMPORT.FILE.NAME',
        className: 'text-center',
        width: '200px',
        fixed: 'left',
        index: 'filename',
      },
      {
        title: '文件大小',
        i18n: 'BATCH.IMPORT.FILE.SIZE',
        index: 'size',
        width: '300px',
        className: 'text-center',
      },
      {
        title: '状态',
        i18n: 'GENERAL.INFO.STATUS',
        index: 'status',
        width: '100px',
        className: 'text-center',
        render: 'result',
      },
      {
        title: '信息',
        i18n: 'BATCH.FILE.INFO',
        index: 'msg',
        width: '200px',
        className: 'text-center',
        fixed: 'right',
      },
    ]
    this.data = []
    this.batchResult = []
  }
}
